package com.feng.aclservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.feng.aclservice.entity.Permission;
import com.feng.aclservice.entity.RolePermission;
import com.feng.aclservice.mapper.AclPermissionMapper;
import com.feng.aclservice.service.AclPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.aclservice.service.AclRolePermissionService;
import com.feng.commonutils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限 服务实现类
 * </p>
 *
 * @author fengge
 * @since 2023-04-02
 */
@Service
public class AclPermissionServiceImpl extends ServiceImpl<AclPermissionMapper, Permission> implements AclPermissionService {
      @Autowired
      private AclRolePermissionService aclRolePermissionService;
    @Override
    public R queryAllMenuGuli() {
        //先查询所有菜单
        List<Permission> list = this.list(null);
        //查询一级菜单
        list.stream().filter(e->{
           return e.getPid().equals("0");
        }).map(a->{
            a.setLevel(1);
            a.setChildren(getChildren(a,list));
            //设置层级为1

            return a;
        }).collect(Collectors.toList());
        return R.ok().data("hildren",list);
    }

    @Override
    public R removeChildrenByid(String id) {
        //用于删除菜单的所有id
        List<String> permissions=new ArrayList<>();
        //2 向集合里面设置删除菜单的id
        this.selectPermissionChildById(id,permissions);
        //同时需要把当前id也装进去
        permissions.add(id);
        this.removeByIds(permissions);
        return R.ok().message("删除成功");
    }

    @Override
    public R saveRolePermissionRealtionShipGuli(String roleId, String[] permissionId) {

        List<RolePermission> list=new ArrayList<>();
        //对每个permissionid进行遍历
        for (String permission : permissionId) {
            RolePermission rolePermission=new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permission);
            list.add(rolePermission);
        }
        //添加
        aclRolePermissionService.saveBatch(list);
        return R.ok();
    }

    @Override
    public List<Permission> selectAllMenu(String roleId) {
        //首先先根据角色id获得对应的权限id
        //如role_id与permission_id
        LambdaQueryWrapper<RolePermission> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId,roleId);
        //获取该角色对应的权限id
        List<RolePermission> rolePermissions = aclRolePermissionService.list(queryWrapper);
        //获取所有的权限信息
        List<Permission> list = this.list(null);
        for(int i=0;i<list.size();i++){
            Permission permission = list.get(i);
            for(int m=0;m<rolePermissions.size();m++){
                RolePermission rolePermission = rolePermissions.get(m);
                if(permission.getId().equals(rolePermission.getPermissionId())){
                  permission.setSelect(true);
                }
            }
        }
        List<Permission> permissionList = bulid(list);
        return permissionList;
    }
    /**
     * 使用递归方法建菜单
     * @param treeNodes
     * @return
     */
    private static List<Permission> bulid(List<Permission> treeNodes) {
        List<Permission> trees = new ArrayList<>();
        for (Permission treeNode : treeNodes) {
            if ("0".equals(treeNode.getPid())) {
                treeNode.setLevel(1);
                trees.add(findChildren(treeNode,treeNodes));
            }
        }
        return trees;
    }
    /**
     * 递归查找子节点
     * @param treeNodes
     * @return
     */
    private static Permission findChildren(Permission treeNode,List<Permission> treeNodes) {
        treeNode.setChildren(new ArrayList<Permission>());

        for (Permission it : treeNodes) {
            if(treeNode.getId().equals(it.getPid())) {
                int level = treeNode.getLevel() + 1;
                it.setLevel(level);
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(it,treeNodes));
            }
        }
        return treeNode;
    }

    private void selectPermissionChildById(String id, List<String> permissions) {
        LambdaQueryWrapper<Permission> queryWrapper=new LambdaQueryWrapper<>();
        //id与其pid相等，查出下一级菜单
        queryWrapper.eq(Permission::getPid,id);
        queryWrapper.select(Permission::getId);
        //进行查询
        List<Permission> list = this.list(queryWrapper);
        list.stream().forEach(e->{
            permissions.add(e.getId());
            //递归查询
            this.selectPermissionChildById(e.getId(),permissions);
        });

    }

    private List<Permission> getChildren(Permission a, List<Permission> list) {

        List<Permission> collect = list.stream().filter(e -> {

            return e.getPid().equals(a.getId());
        }).map(b -> {
             b.setLevel(a.getLevel()+1);
            b.setChildren(getChildren(b, list));
            return b;
        }).collect(Collectors.toList());
        return collect;
    }
}
